#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>

int ticket = 1000;

namespace wjl
{
    class Mutex
    {
    public:
        Mutex()
        {
            pthread_mutex_init(&_lock, nullptr);
        }

        void Lock()
        {
            pthread_mutex_lock(&_lock);
        }

        void UnLock()
        {
            pthread_mutex_unlock(&_lock);
        }

        ~Mutex()
        {
            pthread_mutex_destroy(&_lock);
        }
    private:
        pthread_mutex_t _lock;
    };
}

class LookGuard
    {
    public:
        LookGuard(wjl::Mutex& mutex)
            : _mutex(mutex)
        {
            _mutex.Lock();
        }

        ~LookGuard()
        {
            _mutex.UnLock();
        }
    private:
        wjl::Mutex& _mutex;
};

wjl::Mutex mutex;

void* thread_function(void* arg)
{
    std::string name = (char*)arg;
    while(1)
    {
        LookGuard lookguard(mutex);
        if(ticket > 0)
        {
            usleep(1000);
            std::cout << "我是" << name << ":票还剩" << ticket << std::endl;
            ticket--;
        }
        else
        {
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, nullptr); // 初始化锁

    pthread_t t1;
    pthread_t t2;
    pthread_t t3;
    pthread_t t4;

    pthread_create(&t1, nullptr, thread_function, (void *)"Thread-1");
    pthread_create(&t2, nullptr, thread_function, (void *)"Thread-2");
    pthread_create(&t3, nullptr, thread_function, (void *)"Thread-3");
    pthread_create(&t4, nullptr, thread_function, (void *)"Thread-4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    pthread_mutex_destroy(&lock); // 设置的非全局锁需要手动进行释放，但是全局的锁不需要手动释放

    return 0;
}